#!/usr/bin/env bash

_devops_subcommands="install uninstall completion install-completion status"
_usage()
{
  echo 'usage ' >&2
  echo ' '$(basename $0)' [-h] '$(echo $_devops_subcommands|sed 's/ /|/g') >&2
  exit 0
}

_devops_completion()
{
  __devops_completion()
  {
    local _cur _prev _opts
    COMPREPLY=()
    _cur="${COMP_WORDS[COMP_CWORD]}"
    _prev="${COMP_WORDS[COMP_CWORD-1]}"
    _opts="-h --help install uninstall completion install-completion status"
    case "${_prev}" in
      -h|--help)
        local base=${COMP_WORDS[COMP_CWORD-2]}
        case "${base}" in
          *)
            return 0
            ;;
        esac
        ;;
      *)
        if (( ${#COMP_WORDS[@]} > 2 )); then
          local _options=$(eval "${COMP_WORDS[@]:0:$((${#COMP_WORDS[@]}-1))} options")
          COMPREPLY=( $(compgen -W "${_options}" -- ${_cur}) )
          return 0
        fi
        ;;
    esac
    COMPREPLY=($(compgen -W "${_opts}" -- ${_cur}))  
    return 0
  }
  complete -F __devops_completion devops
}

_devops_install_completion()
{
  if [[ -d /usr/local/etc/bash_completion.d ]]; then
    $0 completion > /usr/local/etc/bash_completion.d/$(basename $0)
  fi
}

_devops_status()
{
  kubectl get ns -oname 2>/dev/null | grep mpi-operator 1>/dev/null 2>/dev/null
  if (( $? == 0 )); then
    echo '📦 installed'
  else
    echo '📦 not installed'
  fi
}

_reverse() {
  local _result=() _i=$(($# - 1)) _item _args=()
  for _arg; do
    _args+=("$_arg")
  done
  while (( $_i >= 0 )); do
    _item=${_args[$_i]}
    _result+=( $_item )
    _i=$(($_i-1))
  done
  echo ${_result[@]}
}

_kubectl_action()
{
  local _array=() _dir _path=$1 _action=$2 _list=("operators")
  if [[ $_action == delete ]]; then
    _array=( $(_reverse ${_list[@]}) )
  else
    _array=( ${_list[@]} )
  fi
  for _dir in "${_array[@]}"; do
    echo kubectl -k $_path/$_dir $_action
    kubectl -k $_path/$_dir $_action
  done
}

_main()
{
  local _kustomize_path=${0%%/scripts*}/k8s/devops
  while [[ "$#" -gt "0" && $1 =~ ^- ]]; do
    case "$1" in
      -h|--help)
          _usage
          exit 0
          ;;
      *)
          echo 'unknown option '$1
          shift
          exit 1
          ;;
    esac
  done
  case "$#" in
    0) 
      _usage
      ;;
    1)
      case "$1" in 
        completion)
          type _devops_completion | sed '1,3d;$d'
          ;;
        install)
          _kubectl_action $_kustomize_path apply
          ;;
        install-completion)
          _devops_install_completion
          ;;
        options)
          echo '-h --help '$(echo $_devops_subcommands)' options '
          return 0
          ;;
        status)
          _devops_status
          ;;
        uninstall)
          _kubectl_action $_kustomize_path delete
          ;;
        *)
          echo 'unknown option '$1 >&2
          _usage
          ;;
      esac
      ;;
    *) 
      shift
      echo 'unknown options '$@ >&2
      ;;
  esac
}

_main $@
        

